package com.iotimc.attendancesystem.util;

import android.os.Environment;
import android.util.Log;

import com.iotimc.attendancesystem.entity.AttendanceLogEntity;
import com.iotimc.attendancesystem.entity.DoorLogEntity;
import com.iotimc.attendancesystem.entity.PersonEntity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import jxl.Workbook;

/**
 * Created by david on 2017/12/29.
 */

public class JxlWriteExcel {
    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String TAG = "JxlWriteExcel";
    private static final String[] attendanceTitles = {"头像", "编号", "姓名", "卡号", "考勤时间"};

    public static byte[] excel(List<AttendanceLogEntity> logEntities) {
        try {

            // 构建Workbook对象, 只读Workbook对象
            // Method 1：创建可写入的Excel工作薄
//            WritableWorkbook wwb = Workbook.createWorkbook(new File(
//                    Environment.getExternalStorageDirectory().getPath()+"/test.xls"));
            // Method 2：将WritableWorkbook直接写入到输出流
            Log.i(TAG, "excel: " + Environment.getExternalStorageDirectory().getPath());
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);


            jxl.write.WritableSheet ws = wwb.createSheet("Sheet", 0);

            ws.setColumnView(0, 15);
            ws.setColumnView(1, 25);
            ws.setColumnView(2, 20);
            ws.setColumnView(3, 25);
            ws.setColumnView(4, 25);
            for (int i = 0; i < attendanceTitles.length; i++) {
                ws.addCell(new jxl.write.Label(i, 0, attendanceTitles[i]));
            }

            for (int i = 1; i <= logEntities.size(); i++) {
                ws.setRowView(i, 252*6);
                AttendanceLogEntity logEntity = logEntities.get(i - 1);
                PersonEntity personEntity = logEntity.getPersonEntity();
                if (logEntity.getCaptureImage() != null) {
                    jxl.write.WritableImage f = new jxl.write.WritableImage(0, i,
                            1, 1, logEntity.getCaptureImage());
                    ws.addImage(f);
                }
                ws.addCell(new jxl.write.Label(1, i, personEntity.getCode()));
                ws.addCell(new jxl.write.Label(2, i, personEntity.getName()));
                ws.addCell(new jxl.write.Label(3, i, personEntity.getCard()));
                ws.addCell(new jxl.write.Label(4, i, simpleDateFormat.format(logEntity.getCreateTime())));
            }


            wwb.write();
            wwb.close();
            return os.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
